package com.cuz.for2024;

public class T64 {

    public static void main(String[] args) {
        int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
        System.out.println(new T64().minPathSum(grid));
    }


    public int minPathSum(int[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        int[][] dp = new int[row][col];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (i == 0 && j == 0) {
                    dp[i][j] = grid[0][0];
                } else {
                    dp[i][j] = Math.min(get(dp, i - 1, j), get(dp, i, j - 1)) + grid[i][j];
                }
            }
        }
        return dp[row-1][col-1];
    }

    private int get(int[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
            return Integer.MAX_VALUE;
        }
        return grid[i][j];
    }


}
